import { ipcMain, IpcMainInvokeEvent } from 'electron'
import HttpService from '../services/http-service'
import type { HttpRequestConfig, HttpResponse } from '../../common/types/http-ipc'

/**
 * IPC 处理器
 * 处理渲染进程与主进程之间的通信
 */
class IPCHandlers {
  private httpService: HttpService

  constructor() {
    this.httpService = new HttpService()
    this.registerHandlers()
  }

  private registerHandlers(): void {
    // ==================== HTTP API 调用 ====================

    ipcMain.handle('http-request', async (event: IpcMainInvokeEvent, config: HttpRequestConfig) => {
      try {
        console.log('[IPC] HTTP request:', config)
        const result = await this.httpService.request(config)
        return result
      } catch (error) {
        const err = error as Error
        console.error('[IPC] HTTP request failed:', err)
        return {
          success: false,
          error: {
            code: 'IPC_ERROR',
            message: err.message || 'IPC 通信失败',
            details: err
          },
          status: 0
        }
      }
    })

    // ==================== 认证相关 ====================

    ipcMain.handle('api-login', async (event: IpcMainInvokeEvent, phone: string, password: string) => {
      return await this.httpService.login(phone, password)
    })

    ipcMain.handle('api-register', async (event: IpcMainInvokeEvent, phone: string, password: string, name?: string) => {
      return await this.httpService.register(phone, password, name)
    })

    ipcMain.handle('api-send-code', async (event: IpcMainInvokeEvent, phone: string, type: number) => {
      console.log('[IPC] Send verification code:', { phone, type })
      try {
        const result = await this.httpService.sendCode(phone, type)
        console.log('[IPC] Send verification code result:', result)
        return result
      } catch (error) {
        console.error('[IPC] Send verification code error:', error)
        throw error
      }
    })

    ipcMain.handle('api-login-with-code', async (event: IpcMainInvokeEvent, phone: string, code: string) => {
      console.log('[IPC] Login with code:', { phone, code })
      try {
        const result = await this.httpService.loginWithCode(phone, code)
        console.log('[IPC] Login with code result:', result)
        return result
      } catch (error) {
        console.error('[IPC] Login with code error:', error)
        throw error
      }
    })

    ipcMain.handle('api-register-with-code', async (event: IpcMainInvokeEvent, phone: string, code: string) => {
      console.log('[IPC] Register with code:', { phone, code })
      try {
        const result = await this.httpService.registerWithCode(phone, code)
        console.log('[IPC] Register with code result:', result)
        return result
      } catch (error) {
        console.error('[IPC] Register with code error:', error)
        throw error
      }
    })

    // ==================== 主页管理 ====================

    ipcMain.handle('api-get-homepages', async () => {
      return await this.httpService.getHomePages()
    })

    ipcMain.handle('api-add-homepage', async (event: IpcMainInvokeEvent, homepage: any) => {
      return await this.httpService.addHomePage(homepage)
    })

    ipcMain.handle('api-update-homepage', async (event: IpcMainInvokeEvent, id: string, updates: any) => {
      return await this.httpService.updateHomePage(id, updates)
    })

    ipcMain.handle('api-delete-homepage', async (event: IpcMainInvokeEvent, id: string) => {
      return await this.httpService.deleteHomePage(id)
    })

    // ==================== 视频相关 ====================

    ipcMain.handle('api-get-videos', async (event: IpcMainInvokeEvent, profileId?: string) => {
      return await this.httpService.getVideos(profileId)
    })

    // ==================== 抖音相关 ====================

    ipcMain.handle('api-get-douyin-main-page-info', async (event: IpcMainInvokeEvent, url: string) => {
      try {
        console.log('[IPC] Get Douyin main page info:', url)
        const result = await this.httpService.getDouyinMainPageInfo(url)
        console.log('[IPC] Get Douyin main page info result:', result)
        return result
      } catch (error) {
        console.error('[IPC] Get Douyin main page info error:', error)
        throw error
      }
    })

    // ==================== 认证令牌管理 ====================

    ipcMain.handle('set-auth-token', async (event: IpcMainInvokeEvent, token: string | null) => {
      this.httpService.setAuthToken(token)
      console.log('[IPC] Auth token set:', token ? 'Token provided' : 'Token cleared')
      return { success: true }
    })
  }
}

export default IPCHandlers